Escape analysis is a compile-time optimization where the Go compiler decides whether a variable can live on the stack (fast, automatically freed) or must be heap-allocated (GC-managed) based on its lifetime.
The compiler performs escape analysis to minimize heap allocations, reducing GC pressure. A variable escapes to the heap when its lifetime exceeds the function frame or when its size is dynamically determined.
Returned by pointer: the caller holds the reference, variable must outlive the function
Stored in an interface: concrete type is hidden, compiler cannot track lifetime statically
Captured by a goroutine closure: goroutine may outlive the creating function
Size unknown at compile time: dynamic slices and maps
Too large for the stack: objects exceeding the stack size limit